package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class WechatServiceImpl implements WechatService {

    public static final String openIdUrl = "https://api.weixin.qq.com/sns/jscode2session";
    public static final String phoneUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    public static final String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token";

    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;
    @Override
    public String getOpenid(String code) {
        Map<String,Object> sh = new HashMap<>();
        sh.put("appid",appid);
        sh.put("secret",secret);
        sh.put("js_code",code);
        sh.put("grant_type","authorization_code");
        String openId = HttpUtil.get(openIdUrl, sh);
        JSONObject jsonObject = JSONUtil.parseObj(openId);
        String openid = jsonObject.getStr("openid");
        return openid;
    }

    @Override
    public String getPhone(String detailCode) {
        String token = getToken();
        String url = phoneUrl+token;
        Map<String,Object> sh = new HashMap<>();
        sh.put("code",detailCode);
        String phone = HttpUtil.post(url, JSONUtil.toJsonStr(sh));
        JSONObject jsonObject = JSONUtil.parseObj(phone);
        if(jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        String str = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        return str;
    }

    public String getToken(){
        Map<String,Object> sh = new HashMap<>();
        sh.put("appid",appid);
        sh.put("secret",secret);
        sh.put("grant_type","client_credential");
        String token = HttpUtil.get(tokenUrl, sh);
        JSONObject jsonObject = JSONUtil.parseObj(token);
        return jsonObject.getStr("access_token");
    }
}
